package com.wechat.wins.util;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;

/**
 * 证书操作类
 */
public final class CertifcateUtils {

    public static byte[] readCertifacates() throws Exception {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final InputStream in = new FileInputStream("/home/wins/workspace/Java/wechat-mp/src/main/resources/http.crt");
        final java.security.cert.Certificate cate = factory.generateCertificate(in);
        return cate.getEncoded();
    }

    public static byte[] readPrivateKey() throws Exception {
        final KeyStore store = KeyStore.getInstance("JKS");
        final InputStream in = new FileInputStream("/home/wins/workspace/Java/wechat-mp/src/main/resources/http.keystore");
        store.load(in, "wangyi".toCharArray());
        final PrivateKey pk = (PrivateKey) store.getKey("wangyi", "wangyi".toCharArray());
        return pk.getEncoded();
    }

    public static PrivateKey readPrivateKeys() throws Exception {
        final KeyStore store = KeyStore.getInstance("JKS");
        final InputStream in = new FileInputStream("/home/wins/workspace/Java/wechat-mp/src/main/resources/http.keystore");
        store.load(in, "wangyi".toCharArray());
        final PrivateKey pk = (PrivateKey) store.getKey("wangyi", "wangyi".toCharArray());
        return pk;
    }

    public static PublicKey readPublicKeys() throws Exception {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final InputStream in = new FileInputStream("/home/wins/workspace/Java/wechat-mp/src/main/resources/http.crt");
        final java.security.cert.Certificate cate = factory.generateCertificate(in);
        return cate.getPublicKey();
    }

    public static java.security.cert.Certificate createCertiface(final byte[] b) throws Exception {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final InputStream in = new ByteArrayInputStream(b);
        final java.security.cert.Certificate cate = factory.generateCertificate(in);
        return cate;
    }

    public static String byte2hex(final byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }
}